package com.lft.examsys.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lft.examsys.entity.Item;
import com.lft.examsys.entity.Paper;
import com.lft.examsys.entity.Type;
import com.lft.examsys.model.IModel;
import com.lft.examsys.service.ItemService;
import com.lft.examsys.service.PaperService;
import com.lft.examsys.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author ：Qingchen
 * @date ：Created in 2022/4/1 15:30
 * @description：试卷接口
 * @modified By：
 * @version: $
 */
@RestController
@RequestMapping("/paper")
public class PaperController {

    @Autowired
    private PaperService paperService;

    @Autowired
    private ItemService itemService;

    @Autowired
    private TypeService typeService;

    private static String elName = "papers";

    @GetMapping("/manage")
    @PreAuthorize("hasAnyAuthority('paper.manage')")
    public ModelAndView manage(IModel model, Integer page, Integer size) {
        return model.validation("admin/PaperManage", () -> {
            paperService.getAllByPage(model,page,size, elName);
            Map<Object, Object> res = paperService.getPaperCount();
            model.add("itemsCount",res);
        }, model::err);
    }

    @GetMapping("/edit/{id}")
    @PreAuthorize("hasAnyAuthority('paper.edit')")
    public ModelAndView editPaper(IModel model, @PathVariable Integer id, Integer page, Integer size) {
        return model.validation("admin/PaperEdit", () -> {
            Paper paper = paperService.getPaperById(id);
            Map<Object, Object> res = paperService.getPaperCount();
            model.add("itemsCount",res);
            model.add("paper", paper);
            model.add("page", page);
            model.add("size", size);
        }, model::err);
    }

    @GetMapping("/itemsManage")
    @PreAuthorize("hasAnyAuthority('paper.edit')")
    public ModelAndView paperItemsManage(IModel model, Integer id, Integer page, Integer size) {
        return model.validation("admin/PaperItemsManage", () -> {
            Page<Item> pageInfo = new Page<>(page == null?1:page, size == null?10:size);
            Paper paper = paperService.getPaperById(id);
            Page<Item> itemList = itemService.getAllByPaperId(id, pageInfo);
            model.add("paper", paper);
            model.add("itemes", itemList.getRecords());
            model.add("page", itemList.getCurrent());
            model.add("size", itemList.getSize());
            model.add("total", itemList.getPages());
            model.add("count", itemList.getTotal());
            model.add("test","1");
        }, model::err);
    }



    /**
     *
     * @param paperId 试卷id
     * @param itemId 要删除的题目id
     * @param page  页数
     * @param size  每页数量
     * @return
     */
    @PostMapping("/deleteItem")
    @PreAuthorize("hasAnyAuthority('paper.deleteItem')")
    public ModelAndView deleteItem(IModel model, Integer paperId, Integer itemId, Integer page, Integer size) {
        return model.validation("admin/PaperEdit", () -> {
            if (paperService.deleteItem(paperId, itemId)) {
                Paper paper = paperService.getPaperById(paperId);
                List<Item> itemList = itemService.getItemByPaperId(paperId);
                model.add("paper", paper);
                model.add("itemes", itemList);
                paperService.getAllByPage(model, page, size, "");
            }
        }, model::err);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAnyAuthority('paper.update')")
    public ModelAndView updatePaper(IModel model, Integer id, String title, String begin, Integer limitation, Integer page, Integer size) {
        return model.validation("redirect:/paper/manage?page=" + page +"&size=" + size, () -> {
            //TODO: 保存试卷
            Paper paper = paperService.getPaperById(id);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String time = begin.replace("T"," ");
            Date date = simpleDateFormat.parse(time);
            paper.setTitle(title);
            paper.setBegin(date);
            paper.setLimitation(limitation);
            if (paperService.updatePaper(paper) == 0) {
                model.err("更新试卷失败！");
            }
        }, model::err);
    }

    @PostMapping("/delete")
    @PreAuthorize("hasAnyAuthority('paper.delete')")
    public ModelAndView deletePaper(IModel model, Integer id, Integer page, Integer size) {
        return model.validation("admin/PaperManage", () -> {
            if (paperService.deletePaper(id) < 0 ) {
                model.err("删除失败");
            } else {
                model.redirectTo("/paper/manage");
            }
        }, model::err);
    }

    @GetMapping("/item/edit/{itemId}")
    @PreAuthorize("hasAnyAuthority('paper.itemEdit')")
    public ModelAndView editItem(IModel model, @PathVariable Integer itemId, Integer paperId, Integer page, Integer size) {
        return model.validation("admin/PaperItemEdit", () -> {
            Item item = itemService.getItem(itemId);
            List<Type> types = typeService.getTypeNames();
            model.add("item",item);
            model.add("types", types);
            model.add("paperId", paperId);
            model.add("page", page);
            model.add("size", size);
        }, model::err);
    }

    @PostMapping("/item/update")
    @PreAuthorize("hasAnyAuthority('paper.itemUpdate')")
    public ModelAndView updateItem(IModel model, Integer page, Integer size, Integer paperId, Item item) {
        return model.validation("redirect:/paper/itemsManage?id="+ paperId + "&page=" + page + "&size=" + size, () -> {
            itemService.saveItem(item);
        }, model::err);
    }

    @GetMapping("/toGenerate")
    @PreAuthorize("hasAnyAuthority('paper.toGenerate')")
    public ModelAndView toGenerate (IModel model) {
        return model.validation("admin/PaperGenerate", () -> {
            //这是一个跳转方法，不需要任何参数
        }, model::err);
    }

    @PostMapping("/generate")
    @PreAuthorize("hasAnyAuthority('paper.generate')")
    public ModelAndView generatePaper(IModel model, String title, String begin, Integer limitation, Integer amount) {
        return model.validation("admin/PaperManage", () -> {
            Paper paper = new Paper();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String time = begin.replace("T"," ");
            Date date = simpleDateFormat.parse(time);
            paper.setTitle(title);
            paper.setBegin(date);
            paper.setLimitation(limitation);
            paperService.savePaper(paper);
            Integer id = paperService.getMaxId();
            List<Item> itemList = itemService.randomItems(amount);
            for (Item item : itemList) {
                if (paperService.insertPaperItem(item.getId(), id)) {

                }else {
                    model.err("插入试卷题目表失败");
                }
            }
            model.redirectTo("/paper/manage");
        }, model::err);
    }

}
